package com.smile.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * SaToken 自动配置类
 * 确保 SaToken 上下文过滤器和拦截器正确初始化
 */
@Configuration
@ConditionalOnClass(StpUtil.class)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@Order(2)
public class SaTokenAutoConfiguration implements WebMvcConfigurer {

//    @Bean
//    public SaCorsHandleFunction corsHandle() {
//        return (req, res, sto) -> {
//            res.
//                    // 允许指定域访问跨域资源
//                    setHeader("Access-Control-Allow-Origin", "*")
//                    // 允许所有请求方式
//                    .setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE")
//                    // 有效时间
//                    .setHeader("Access-Control-Max-Age", "3600")
//                    // 允许的header参数
//                    .setHeader("Access-Control-Allow-Headers", "*");
//
//            // 如果是预检请求，则立即返回到前端
//            SaRouter.match(SaHttpMethod.OPTIONS)
//                    .free(r -> System.out.println("--------OPTIONS预检请求，不做处理"))
//                    .back();
//        };
//    }

    /**
     * 注册 SaToken 上下文过滤器
     * 这是 SaToken 工作的基础，必须在所有其他组件之前初始化
     */
//    @Bean
//    public FilterRegistrationBean<SaTokenContextFilterForServlet> saTokenContextFilter() {
//        System.out.println("=== 自动配置：初始化 SaToken 上下文过滤器 ===");
//        FilterRegistrationBean<SaTokenContextFilterForServlet> bean = new FilterRegistrationBean<>();
//        bean.setFilter(new SaTokenContextFilterForServlet());
//        bean.addUrlPatterns("/*");
//        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
//        bean.setAsyncSupported(true);
//        bean.setDispatcherTypes(EnumSet.of(DispatcherType.ASYNC, DispatcherType.REQUEST));
//        System.out.println("=== 自动配置：SaToken 上下文过滤器初始化完成 ===");
//        return bean;
//    }

    @Autowired
    private PermissionInterceptor permissionInterceptor;

    /**
     * 注册 SaToken 拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        System.out.println("=== 自动配置：注册 SaToken 拦截器 ===");
        registry.addInterceptor(new SaInterceptor(handle -> {
                    System.out.println("=== SaToken 拦截器执行登录检查 ===");
                    StpUtil.checkLogin();
                }))
                .addPathPatterns("/**")
                .excludePathPatterns(
                        "/menu/listAll",
                        "/test/es/add",
                        "/test/es/select",
                        "/sso/doLogin"
                        , "/shopping/auth/doLogin"
                        , "/shopping/auth/logout"
                        , "/logout"
                        , "/user/getUserInfoByUserName"
                        , "/role/getRoleById"
                        , "/menu/getMenusByRoleId"
                        , "/menu/list"
                        , "/log/login/addLoginLog"
                        , "/airport/**"
                        , "/drone/**"
                        , "/fly/**"
                        , "/ws/**"
                        , "/api/monitor/ws/**"
                        , "/live/**"
                        , "/payload/**",
                        "/organization/getOrganizationById",
                        "/onSiteInspection/executeOnSiteInspection",
                        "/onSiteInspection/editOnSiteInspection",
                        "/flightTask/prepare"
                );

        registry.addInterceptor(permissionInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(
                        "/test/es/add",
                        "/test/es/select",
                        "/sso/doLogin"
                        , "/shopping/auth/doLogin"
                        , "/shopping/auth/logout"
                        , "/logout"
                        , "/user/getUserInfoByUserName"
                        , "/role/getRoleById"
                        , "/menu/getMenusByRoleId"
                        , "/menu/list"
                        , "/menu/listAll"
                        , "/log/login/addLoginLog"
                        , "/airport/**"
                        , "/drone/**"
                        , "/fly/**"
                        , "/ws/**"
                        , "/live/**",
                        "/organization/getOrganizationById",
                        "/onSiteInspection/executeOnSiteInspection",
                        "/onSiteInspection/editOnSiteInspection",
                        "/flightTask/prepare"
                );

        System.out.println("=== 自动配置：SaToken 拦截器注册完成 ===");
    }
}